package com.lemon.smartsafety.ui.activity.fire.item;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.entity.event.base.NewAppEvent;
import com.lemon.smartsafety.entity.safe.company.CompanyInfo;
import com.lemon.smartsafety.http.HttpBack;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.result.BaseMode;
import com.lemon.smartsafety.result.fire.SuperviseCompanyResult;
import com.lemon.smartsafety.result.fire.SuperviseTargetResult;
import com.lemon.smartsafety.tag.fire.FirefightingManageTAG;
import com.lemon.smartsafetynew.ui.activity.base.NewBaseActivity;
import com.lemon.smartsafety.ui.activity.fire.FirefightingUtil;
import com.lemon.smartsafety.ui.adapter.fire.FirefightingManageAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.SystemUtil;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.view.ViewFireCompanyNone;
import com.lemon.smartsafety.view.list.ListRefreshView;
import com.lemon.smartsafety.view.pop.PopFireManage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;


/**
 * 项目名称：workspace
 * 类描述：
 * 创建人：Fargo
 * 创建时间：2016/8/9 11:33
 * 修改人：Fargo
 * 修改时间：2016/8/9 11:33
 * 修改备注：   监督管理
 */
public class FirefightingManageActivity extends NewBaseActivity {

    @Bind(R.id.main_title)
    TextView mainTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @Bind(R.id.txt_search)
    TextView txtSearch;
    @Bind(R.id.et_search)
    EditText etSearch;
    @Bind(R.id.txt_mode)
    TextView txtMode;
    @Bind(R.id.lineMode)
    LinearLayout lineMode;
    @Bind(R.id.listView)
    ListRefreshView listView;
    @Bind(R.id.swipe_layout)
    SwipeRefreshLayout swipeLayout;
    @Bind(R.id.line)
    View line;
    @Bind(R.id.viewFireCompanyNone)
    ViewFireCompanyNone viewFireCompanyNone;
    @Bind(R.id.txt_score)
    TextView txtScore;
    @Bind(R.id.lineScore)
    LinearLayout lineScore;


    private CompanyInfo mCompanyInfo;
    private String[] mode = {"综合", "人员覆盖率", "设施完好率", "哥那里及时率", "信息完善率", "户籍化上报率"};
    private String[] score = {"0~100","0~30", "30~60", "60~100"};
    private FirefightingManageAdapter firefightingManageAdapter;
    private SuperviseTargetResult superviseTargetResult;
    private SuperviseCompanyResult superviseCompanyResult;

    //TAB
    private List<SuperviseTargetResult.ResultEntity> mTabList;
    private List<String> mTabStringList;
    private List<String> mTabStringListScore;

    //List数据
    private List<SuperviseCompanyResult.ResultEntity> mList;

    private String strSearch = "";
    private String strTabCode = "";
    private String strScoreCode = "";
    private String strSuperviseTypeCode = "";

    //（1：所有，2：我的），可不传，后台默认为1
    private int type_id = 1;


    //综合界面出入的值
    private int transType=-1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RefreshTAG = mActivity.getClass().getName();
    }

    @Override
    protected void getBundleArgs() {
        if (getIntent().getExtras() != null) {
            mCompanyInfo = (CompanyInfo) getIntent().getSerializableExtra(BundleKey.COMPANY_INFO);
        }

        if(getIntent().getExtras().containsKey(BundleKey.COMPANY_INFO_TYPE)){
            transType=getIntent().getIntExtra(BundleKey.COMPANY_INFO_TYPE,-1);
        }

        if(getIntent().getExtras().containsKey(BundleKey.SUPERVISE_TYPE_CODE)){
            strSuperviseTypeCode=getIntent().getStringExtra(BundleKey.SUPERVISE_TYPE_CODE);
        }



    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_firefighting_manage;
    }

    @Override
    protected void initTitleView() {
        //mainTitle.setText("副标题");
        setBarTitle("监督管理");
    }

    @Override
    protected void initView() {

        if(transType!=-1){
            if(transType==0){
                type_id=1;
            }else if(transType==1){
                type_id=2;
            }
        }

        mList = new ArrayList<>();

        firefightingManageAdapter = new FirefightingManageAdapter(mActivity, mList);
        listView.setAdapter(firefightingManageAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                intent = new Intent(mActivity, FirefightingManageCompanyActivity.class);
                bundle = new Bundle();
                bundle.putSerializable(BundleKey.FIRE_COMPANY_BASE_INFO, mList.get(position));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        strSearch = "";
        strTabCode = "";
        initLoadeRefresh(listView);
        initSwipRefresh(swipeLayout);

    }


    private void initTab() {
        mTabList = superviseTargetResult.getResult();
        mTabStringList = new ArrayList<>();
        mTabStringListScore=new ArrayList<>();
        if (CommonUtil.listIsEmpty(mTabList)) {
            return;
        }

        for (int i = 0; i < mTabList.size(); i++) {
            mTabStringList.add(mTabList.get(i).getTargetName());
        }

        //初始化分数
        for (int i = 0; i < score.length; i++) {
            mTabStringListScore.add(score[i]);
        }

        txtMode.setText(mTabStringList.get(0));
        strTabCode = mTabList.get(0).getTargetCode();

        txtScore.setText(mTabStringListScore.get(0));
        strScoreCode=mTabStringListScore.get(0);

        initList();
    }


    @Override
    protected void initHttp() {
        httpTab();
    }

    @Override
    protected void initList() {
        current_page = 1;
        httpList();
        listView.setIsload(true);
    }

    @Override
    protected void loadList() {
        if (mList.size() % page_size == 0) {
            current_page = current_page + 1;
            httpList();
        } else {
            showUpLoad(false, listView);
            listView.setIsload(false);
            ToastUtil.show("没有更多数据了");
        }
    }

    @Override
    protected void refreshView() {

    }

    @Override
    protected void callFinish() {
        mActivity.finish();
    }

    @Subscribe
    public void onEventMainThread(final NewAppEvent event) {

        if (event.getTag().equals(RefreshTAG)) {
            try {
                showUpLoad(false, listView);
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (current_page == 1) {
                mList.clear();
            }
            if (!CommonUtil.objIsEmpty(superviseCompanyResult)) {
                if (!CommonUtil.listIsEmpty(superviseCompanyResult.getResult())) {
                    mList.addAll(superviseCompanyResult.getResult());
                    firefightingManageAdapter.notifyDataSetChanged();
                }
            }


            if (CommonUtil.listIsEmpty(mList)) {
                viewFireCompanyNone.setVisibility(View.VISIBLE);
                showSwipLayout(swipeLayout, false);
                viewFireCompanyNone.setContent(event.getMsg());
                viewFireCompanyNone.setSearch("重试");
                viewFireCompanyNone.setAllClick(new ViewFireCompanyNone.AllClick() {
                    @Override
                    public void click() {
                        LogUtils.LOGE("点击了重试");
                        initList();
                    }
                });
            } else {
                viewFireCompanyNone.setVisibility(View.GONE);
                showSwipLayout(swipeLayout, true);

                if (current_page == 1) {
                    LogUtils.LOGE("滑动到顶部");
                    listView.smoothScrollToPosition(0);
                }
            }

        } else if (event.getTag().equals(FirefightingManageTAG.TAG_superviseTargetResult)) {
            initTab();
        }

    }

    @OnClick({R.id.txt_search, R.id.lineMode, R.id.lineScore})
    public void onButtonClick(View v) {
        switch (v.getId()) {
            case R.id.txt_search:
                LogUtils.LOGE(etSearch.getText().toString());
                strSearch = etSearch.getText().toString().trim();
                initList();
                SystemUtil.HideKeyboard(mActivity);
                break;
            case R.id.lineMode:
                PopFireManage.showPopupGeometry(mActivity, line, mTabStringList, txtMode.getText().toString().trim(), new PopFireManage.ClickSureBackInterface() {
                    @Override
                    public void callBackFunction(int item) {
                        txtMode.setText(mTabStringList.get(item));
                        strSearch = etSearch.getText().toString().trim();
                        strTabCode = mTabList.get(item).getTargetCode();
                        listView.smoothScrollBy(0, 0);
                        initList();
                    }
                });
                break;
            case R.id.lineScore:
                PopFireManage.showPopupGeometry(mActivity, line, mTabStringListScore, txtScore.getText().toString().trim(), new PopFireManage.ClickSureBackInterface() {
                    @Override
                    public void callBackFunction(int item) {
                        txtScore.setText(mTabStringListScore.get(item));
                        strSearch = etSearch.getText().toString().trim();
                        strScoreCode = (mTabStringListScore.get(item));
                        listView.smoothScrollBy(0, 0);
                        initList();
                    }
                });
                break;
            default:
                break;
        }
    }


    /**
     * 列表请求
     */
    private void httpList() {
        if (!bPutHttp) {
            superviseCompanyResult = null;
            bPutHttp = true;
            strSearch = etSearch.getText().toString().trim();
            LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
            params.put("page_size", String.valueOf(page_size));
            params.put("current_page", String.valueOf(current_page));

            params.put("company_code", mCompanyInfo.getCompany_code());
            params.put("keywords", strSearch);
            params.put("target_code", strTabCode);
            params.put("type_id", type_id);
            params.put("supervise_type_code", strSuperviseTypeCode);

            params.put("start_score", FirefightingUtil.getScoreFront(strScoreCode));
            params.put("end_score", FirefightingUtil.getScoreLater(strScoreCode));

            showLoading("");
            HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_supervise_company), "", new HttpOkBase.HttpInterface() {
                @Override
                public void callBackFunction(boolean httpClient, String result) {

                    dismissLoading();
                    bPutHttp = false;
                    if (httpClient) {
                        BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                        if (!CommonUtil.objIsEmpty(baseMode)) {
                            if (HttpBack.httpBackError(baseMode)) {

                                try {
                                    superviseCompanyResult = mGson.fromJson(result, SuperviseCompanyResult.class);
                                    EventBus.getDefault().post(new NewAppEvent(RefreshTAG, baseMode.getMsg()));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } else if (baseMode.getCode().equals("1003")) {
                                superviseCompanyResult = mGson.fromJson(result, SuperviseCompanyResult.class);
                                EventBus.getDefault().post(new NewAppEvent(RefreshTAG, baseMode.getMsg()));
                                ToastUtil.show(baseMode.getMsg());
                            } else {
                                EventBus.getDefault().post(new NewAppEvent(RefreshTAG, baseMode.getMsg()));
                                ToastUtil.show(baseMode.getMsg());
                            }
                            firefightingManageAdapter.notifyDataSetChanged();
                        }
                    } else {
                        if (current_page == 1) {
                            EventBus.getDefault().post(new NewAppEvent(RefreshTAG, "网络异常"));
                        }
                    }
                }
            });
        }

    }


    /**
     * 初始化TAB
     */
    private void httpTab() {

        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        showLoading("");
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_supervise_target), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                dismissLoading();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {
                            try {
                                superviseTargetResult = mGson.fromJson(result, SuperviseTargetResult.class);
                                EventBus.getDefault().post(new NewAppEvent(FirefightingManageTAG.TAG_superviseTargetResult));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            ToastUtil.show(baseMode.getMsg());
                        }

                    }
                }
            }
        });
    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        Log.e("onPrepareOptionsMenu", "onPrepareOptionsMenu");
        menu.clear();
        //（1：所有，2：我的），可不传，后台默认为1
        if (type_id == 1) {
            getMenuInflater().inflate(R.menu.menu_me, menu);
        } else {
            getMenuInflater().inflate(R.menu.menu_all, menu);
        }

        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_fire_all) {
            //点击切换所有
            showUpLoad(false, listView);
            type_id = 1;
            invalidateOptionsMenu();
            LoggerHelper.error(getClass(), "点击切换所有");
            mList.clear();
            firefightingManageAdapter.notifyDataSetChanged();

            initList();

        } else if (item.getItemId() == R.id.action_fire_me) {
            //点击切换我的
            showUpLoad(false, listView);
            type_id = 2;
            invalidateOptionsMenu();
            LoggerHelper.error(getClass(), "点击切换我的");
            mList.clear();
            firefightingManageAdapter.notifyDataSetChanged();

            initList();
        }

        return super.onOptionsItemSelected(item);
    }


}
